package com.itheima.appserver.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.appserver.interceptor.UserThreadLocal;
import com.itheima.appserver.service.CommentService;
import com.itheima.commons.constants.Constants;
import com.itheima.commons.pojo.Comment;
import com.itheima.commons.pojo.Publish;
import com.itheima.commons.pojo.UserInfo;
import com.itheima.commons.pojo.Video;
import com.itheima.commons.vo.CommentVo;
import com.itheima.commons.vo.PageResult;
import com.itheima.interfaces.CommentApi;
import com.itheima.interfaces.PublishApi;
import com.itheima.interfaces.UserInfoApi;
import com.itheima.interfaces.VideosApi;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class CommentServiceImpl implements CommentService {

    @Reference
    private CommentApi commentAPI;

    @Reference
    private PublishApi publishAPI;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Reference
    private VideosApi videosAPI;

    @Reference
    private UserInfoApi userInfoAPI;

    /**
     * @param publishId
     * @param page
     * @param pagesize
     */
    @Override
    public PageResult queryCommentsList(String publishId, Integer page, Integer pagesize) {
        List<Comment> commentList = commentAPI.selectByPublishId(publishId, page, pagesize);
        if (CollUtil.isEmpty(commentList)) {
            return new PageResult();
        }
        //拿取评论人的id
        List<Long> userId = CollUtil.getFieldValues(commentList, "userId", Long.class);
        //通过评论人id 查询评论人信息
        Map<Long, UserInfo> publishInfo = userInfoAPI.findUserListByUserIds(null,userId);
        List<CommentVo> commentVos = new ArrayList<>();
        for (Comment comment : commentList) {
            CommentVo commentVo = new CommentVo();
            UserInfo userInfo = publishInfo.get(comment.getUserId());
            commentVo.setId(comment.getId().toHexString());
            commentVo.setAvatar(userInfo.getLogo());
            commentVo.setNickname(userInfo.getNickName());
            commentVo.setContent(comment.getContent());
            commentVo.setCreateDate(comment.getContent());
            Long likeCount = Convert.toLong(redisTemplate.opsForHash().get(Constants.MOVEMENTS_INTERACT_KEY + comment.getId(), Constants.MOVEMENT_LIKE_HASHKEY));
            //缓存中没有去mongodb中找
            if (ObjectUtil.isEmpty(likeCount)) {
                likeCount = commentAPI.selectLikeSize(comment.getId().toHexString());
                //存取到redis中
                redisTemplate.opsForHash().put(Constants.MOVEMENTS_INTERACT_KEY + comment.getId(), Constants.MOVEMENT_LIKE_HASHKEY, likeCount.toString());
            }
            commentVo.setLikeCount(Convert.toInt(likeCount));
            Boolean isLike = redisTemplate.opsForHash().hasKey(Constants.MOVEMENTS_INTERACT_KEY + comment.getId(), Constants.MOVEMENT_ISLIKE_HASHKEY + UserThreadLocal.getUserId());
            //缓存中没有去redis中找
            if (!isLike) {
                isLike = commentAPI.selectIsLike(comment.getId().toHexString(), UserThreadLocal.getUserId());
                //存入redis中
                if (isLike){
                    redisTemplate.opsForHash().put(Constants.MOVEMENT_ISLIKE_HASHKEY+comment.getId(),Constants.MOVEMENT_ISLIKE_HASHKEY+UserThreadLocal.getUserId(),"1");
                }
            }
            commentVo.setHasLiked(isLike ? 1 : 0);
            commentVos.add(commentVo);
        }
        return new PageResult(page, pagesize, Convert.toLong(commentList.size()), commentVos);
    }

    @Override
    public Long likeComment(String publishId) {

        Long likeCount = queryLikeCount(publishId);

        //把这次数据的点赞数量加入到redis中
        redisTemplate.opsForHash().put(Constants.MOVEMENTS_INTERACT_KEY + publishId, Constants.MOVEMENT_ISLIKE_HASHKEY + UserThreadLocal.getUserId(), likeCount.toString());
        //s把自己的点赞从redis中删除
        redisTemplate.opsForHash().put(Constants.MOVEMENTS_INTERACT_KEY + publishId, Constants.MOVEMENT_ISLIKE_HASHKEY + UserThreadLocal.getUserId(), "1");
        return likeCount;
    }

    public Long queryLikeCount(String publishId) {
        Comment comment = new Comment();
        comment.setId(new ObjectId());
        comment.setPublishId(new ObjectId(publishId));
        comment.setCommentType(1);
        comment.setContent(null);
        comment.setUserId(UserThreadLocal.getUserId());
        Publish publish = publishAPI.selectByPublishId(publishId);
        //说明是评论表id
        if (ObjectUtil.isNotEmpty(publish)) {
            comment.setPublishUserId(publish.getUserId());
        } else {
            //可能是评论表和小视频的点赞  去查询id
            Comment isLike = commentAPI.selectById(publishId);
            if (ObjectUtil.isNotEmpty(isLike)) {
                comment.setPublishUserId(isLike.getUserId());
            } else {
                //去小视频表中找
                Video video = videosAPI.selectById(publishId);
                comment.setPublishId(video.getId());
            }
        }

        comment.setIsParent(false);
        comment.setParentId(null);
        comment.setCreated(System.currentTimeMillis());
        Long likeComment = publishAPI.likeComment(comment);
        return likeComment;
    }


    @Override
    public void disLikeComment(String publishId) {
        Long likeComment = publishAPI.NoLikeComment(new ObjectId(publishId), UserThreadLocal.getUserId());
        //把这次数据的点赞数量加入到redis中
        redisTemplate.opsForHash().put(Constants.MOVEMENTS_INTERACT_KEY + publishId, Constants.MOVEMENT_ISLIKE_HASHKEY + UserThreadLocal.getUserId(), likeComment.toString());
        //s把自己的点赞从redis中删除
        redisTemplate.opsForHash().delete(Constants.MOVEMENTS_INTERACT_KEY + publishId, Constants.MOVEMENT_ISLIKE_HASHKEY + UserThreadLocal.getUserId());
    }

    /**
     * 发布评论
     *
     * @param movementId
     * @param comment
     */
    @Override
    public void saveComment(String movementId, String comment) {
        Comment com = new Comment();
        com.setId(new ObjectId());
        com.setPublishId(new ObjectId(movementId));
        com.setCommentType(2);
        com.setContent(comment);
        com.setUserId(UserThreadLocal.getUserId());
        Comment publishUserId = commentAPI.selectPublishUserId(new ObjectId(movementId));
        com.setPublishUserId(publishUserId.getPublishUserId());
        com.setIsParent(false);
        com.setParentId(null);
        com.setCreated(System.currentTimeMillis());

        commentAPI.saveComment(com);
    }
}
